/*

Copyright (c) 2005-2008, Simon Howard

Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

 */

use std::ffi::CStr;
use std::os::raw::c_void;

/* Comparison functions for strings */

#[no_mangle]
pub unsafe extern "C" fn string_equal(string1: *const c_void, string2: *const c_void) -> i32 {
    let c_string1 = CStr::from_ptr(string1 as *const _);
    let c_string2 = CStr::from_ptr(string2 as *const _);
    (c_string1 == c_string2) as i32
}

#[no_mangle]
pub unsafe extern "C" fn string_compare(string1: *const c_void, string2: *const c_void) -> i32 {
    let c_string1 = CStr::from_ptr(string1 as *const _);
    let c_string2 = CStr::from_ptr(string2 as *const _);
    match c_string1.to_bytes().cmp(c_string2.to_bytes()) {
        std::cmp::Ordering::Less => -1,
        std::cmp::Ordering::Greater => 1,
        std::cmp::Ordering::Equal => 0,
    }
}

/* Comparison functions for strings, which ignore the case of letters. */

#[no_mangle]
pub unsafe extern "C" fn string_nocase_equal(string1: *const c_void, string2: *const c_void) -> i32 {
    (string_nocase_compare(string1, string2) == 0) as i32
}

#[no_mangle]
pub unsafe extern "C" fn string_nocase_compare(string1: *const c_void, string2: *const c_void) -> i32 {
    let c_string1 = CStr::from_ptr(string1 as *const _);
    let c_string2 = CStr::from_ptr(string2 as *const _);
    let mut p1 = c_string1.to_bytes().iter();
    let mut p2 = c_string2.to_bytes().iter();

    loop {
        let c1 = p1.next().map(|&c| c.to_ascii_lowercase());
        let c2 = p2.next().map(|&c| c.to_ascii_lowercase());

        match (c1, c2) {
            (Some(c1), Some(c2)) if c1 != c2 => return if c1 < c2 { -1 } else { 1 },
            (Some(_), None) | (None, Some(_)) => return if c1.is_some() { 1 } else { -1 },
            (None, None) => return 0,
            _ => continue,
        }
    }
}